package com.hontech.libratest.activity.fragment.sub

import android.view.View
import android.widget.Button
import android.widget.EditText
import com.hontech.libratest.R
import com.hontech.libratest.activity.window.showProg
import com.hontech.libratest.conn.DeviceConst
import com.hontech.libratest.conn.getCargoType
import com.hontech.libratest.conn.setCargoType
import com.hontech.libratest.utils.onClick
import com.hontech.libratest.utils.toInt
import com.jaredrummler.materialspinner.MaterialSpinner

class CargoSub(view: View) {

    private val etRow = view.findViewById<EditText>(R.id.id_main_et_cargo_row)
    private val sp = view.findViewById<MaterialSpinner>(R.id.id_main_sp_cargo)
    private val btnGet = view.findViewById<Button>(R.id.id_main_btn_cargo_get)
    private val btnSet = view.findViewById<Button>(R.id.id_main_btn_cargo_set)

    init {
        sp.setItems("弹簧货道", "轨道货道", "挂钩货道")
        btnGet.onClick(::onClickGet)
        btnSet.onClick(::onClickSet)
    }

    private suspend fun onClickGet() {
        val row = etRow.toInt()
        val w = showProg(btnGet, "查询第${row}层货道")
        try {
            val id = getCargoType(row)
            val type = DeviceConst.cargoTypeById(id)
            w.success("第${row}层货道类型:$type")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

    private suspend fun onClickSet() {
        val row = etRow.toInt()
        val id = sp.selectedIndex
        val w = showProg(btnGet, "设置第${row}层为:${DeviceConst.cargoTypeById(id)}")
        try {
            setCargoType(row, id)
            w.success("设置成功")
        } catch (e: Exception) {
            e.printStackTrace()
            w.error(e.message!!)
        }
    }

}